/* Gauge - Performance Measurement Framework for Mobile Platforms
 * Copyright (C) 2013, Juha Hytonen <juha.a.hytonen@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.gauge.GaugeAgent;

/**
 * Base class for all runners.
 */
public abstract class AbstractRunner implements Runnable {
	
	private static final int MillisecsToWaitForThread = 100;
	
	private Thread thread;
	
	public final boolean IsRunning() {
		return (thread != null);
	}

	public void Start() {
		thread = new Thread(this);
		thread.start();
	}
	
	public void Stop() throws Exception {
		if (!IsRunning()) return;
		
		thread.interrupt();
		waitForThreadToStop();
		checkIfThreadIsStillRunning();
	}
	
	private void waitForThreadToStop() {
		try {
			thread.join(MillisecsToWaitForThread);
		}
		catch(InterruptedException e) {
		}
	}
	
	private void checkIfThreadIsStillRunning() throws Exception {
		if (IsRunning()) {
			throw new Exception("Thread might not have been stopped");
		}
	}
	
	@Override
	public final void run() {
		execute();
		thread = null;
	}
	
	protected abstract void execute();
	
}
